

#include "Host.hpp"
#include <p2p/Reactor.hpp>
#include <muduo/net/InetAddress.h>

Host::Host(std::unique_ptr<P2PConfig>& config, muduo::net::EventLoop*loop):
            config_(std::move(config)), 
            loop_(loop),
            server_(new muduo::net::TcpServer(loop_,muduo::net::InetAddress(config_->listenAddress, config_->port),"Host"))
{
}

void Host::start()
{
    server_->start();
}

void Host::stop()
{
    {
        std::unique_lock<std::mutex> lock(mtx_);
        peers_.clear();
    }
    loop_->runAfter(3.0, std::bind(&muduo::net::EventLoop::quit, loop_));
}

void Host::addReactor(std::string name, std::shared_ptr<Reactor> &reactor)
{
    std::unique_ptr<std::vector<byte>> reactorChannels(std::move(reactor->getChannels()));
    for(auto i=reactorChannels->begin();i!= reactorChannels->end();i++)
    {
        byte chID = *i;
        chIDs_.push_back(chID);
        reactorBychID_[chID] = reactor;
    }
    reactors_[name] = reactor;
    reactor->setHost(this);
}

std::map<std::string, std::shared_ptr<Reactor>> const& Host::reactors() const
{
    return reactors_;
}

std::shared_ptr<Reactor> Host::reactor(std::string name)
{
    return reactors_[name];
}


void Host::broadcast(byte chID, bytes const& msg)
{

}
